<?php
/**
 * 用户注册api接口
 * @author Jmashimaro
 */
class MemberApp extends FrontendApp {

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 注册第一步先发送验证码
     * 手机短信验证
     */
    public function verify() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        /**过滤参数**/
        $phone_mob = $this->get_gp('phone_mob', 'G');

        /**验证手机号的合法性**/
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号码不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度不是11位！');
        } elseif (!$this->is_number($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '非法的手机号码！');
        }

        /**生成四位随机数的验证码**/
        $verify_code = '';
        for ($i = 0; $i < 4; $i++) {
            $verify_code .= rand(0, 9);
        }

        /**连接短信日志记录中心**/
        $sms = ms('smslogs');

        /**获取手机短信日志信息**/
        $info = $this->get_sms_logs_info($phone_mob);

        /**如果存在手机号码，则更新验证信息**/
        if ($info['phone_mob']) {
            /**一分钟之内不能再次发送验证码**/
            if ((time() - $info['created_at']) < 60) {
                $this->ajax_return(FLAG_ERROR, "已经发送了短信验证码，请您稍后再试！");
            }

            /**当天发送的短信是否超过了十五条**/
            if ($info['count'] >= 15) {
                $this->ajax_return(FLAG_ERROR, "您当天发送的短信验证码已经超过了15条，请您明天再试！");
            }
        }

        $model = m('member');

        /**开启事务**/
        $model->begin();

        /**插入记录**/
        $flag  = $sms->user->verify($phone_mob, $verify_code);
        if (!$flag) {
            $model->rollback();
            $this->ajax_return(FLAG_ERROR, '发送短信失败，请您重试！');
        }

        /**发送手机验证码**/
        $rs = $sms->pm->send($phone_mob, $verify_code);
        if ($rs['code'] != 2) {
            $this->ajax_return(FLAG_ERROR, $rs['msg']);
        }
        /**提交事务**/
        $model->commit();

        $this->ajax_return(FLAG_OK, "发送短信验证码成功！");
    }


    /**
     * 用户注册
     */
    public function register() {
        /**登陆**/
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, "非法的请求！");
        }
        /**过滤参数**/
        $user_name      = $this->get_gp('user_name', 'P');
        $password       = $this->get_gp('password', 'P');
        $phone_mob      = $this->get_gp('phone_mob', 'P');
        $verify_code    = $this->get_gp('verify_code', 'P');

        /**用户名不能为空**/
        if (!$user_name) {
            $this->ajax_return(FLAG_ERROR, "用户名不能为空！");
        }
        /**密码不能为空**/
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, "密码不能为空！");
        }
        /**验证手机号**/
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, "手机号码不能为空！");
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, "请您输入正确的11位手机号码！");
        } elseif (!$this->is_number($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, "手机号码格式不正确！");
        }

        /**验证码**/
        if (!$verify_code) {
            $this->ajax_return(FLAG_ERROR, "验证码不能为空！");
        } elseif (!$this->is_number($verify_code)) {
            $this->ajax_return(FLAG_ERROR, "验证码格式不正确！");
        } elseif (strlen($verify_code) != 4) {
            $this->ajax_return(FLAG_ERROR, "请您输入四位正确的数字验证码！");
        }

        /**用户名是否唯一**/
        if (!$this->check_username($user_name)) {
            $this->ajax_return(FLAG_ERROR, '用户名已经存在！');
        }

        /**手机号码是否唯一**/
        if (!$this->check_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号码已经存在！');
        }

        /**获取手机短信日志信息**/
        $info = $this->get_sms_logs_info($phone_mob);

        /**是否存在用户手机号码信息**/
        if (!$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户手机号码信息不存在！');
        }

        /**验证码是否一致**/
        if ($verify_code != $info['verify_code']) {
            $this->ajax_return(FLAG_ERROR, '短信验证码不正确，请您重新输入！');
        }

        /**验证码时间是否超过半个小时**/
        if ((time() - $info['created_at']) > 1800) {
            $this->ajax_return(FLAG_ERROR, '短信验证码已经超时，请您重新获取！');
        }

        /**连接用户中心**/
        $ms = ms('member');
        $flag = $ms->user->register($user_name, $password, $phone_mob);

        if ($flag) {
            $this->ajax_return(FLAG_OK, "注册成功！");
        } else {
            $this->ajax_return(FLAG_ERROR, "注册失败！");
        }
    }


    /**
     * 用户登陆
     * @see FrontendApp::login()
     */
    public function login() {
        $config = require ROOT_PATH.'/data/config.qiniu.php';
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }

        /**过滤参数**/
        $user_name = $this->get_gp('user_name', 'P');
        $password  = $this->get_gp('password', 'p');

        /**检测用户名**/
        if (!$user_name) {
            $this->ajax_return(FLAG_ERROR, '请您输入用户名！');
        }
        /**检测密码**/
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, '请您输入密码！');
        }
        /**获取用户信息**/
        $info = $this->get_member_info($user_name);
        $info['portrait'] = $info['portrait'] ? $config['qiniu_url'].$info['portrait'] : '';
        /**验证用户名**/
        if (!$info['user_name'] && !$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户名不存在，请您重新输入！');
        }
        /**验证密码**/
        if (sha1(md5($password)) != sha1($info['password'])) {
            $this->ajax_return(FLAG_ERROR, '密码不正确！');
        }

        //token加密方法
        $str = $info['user_id'].'-'.md5('self').'-'.sha1(md5(sha1($info['user_id']).sha1($info['user_name']).sha1($info['password'])));
        $token = base64_encode($str);
        $data['token'] = $token;
        $data['info'] = $info;
        $this->ajax_return(FLAG_OK, '登陆成功！', $data);
    }


    /**
     * 修改密码
     * @author mashimaro
     * @date 2015/03/02
     */
    public function password() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $user_id = $this->get_gp('user_id', 'P');
        $old_pwd = $this->get_gp('old_pwd', 'P');
        $password = $this->get_gp('password', 'P');
        $pwd = $this->get_gp('pwd', 'P');
        if (!$old_pwd) {
            $this->ajax_return(FLAG_ERROR, '旧密码不能为空！');
        }
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, '密码不能为空！');
        }
        if ($password != $pwd) {
            $this->ajax_return(FLAG_ERROR, '密码不一致，请您重新输入！');
        }
        $model = m('member');
        $info = $model->get(array('conditions'=>"user_id={$user_id}"));
        if (!$info) {
            $this->ajax_return(FLAG_ERROR, '用户信息不存在！');
        } elseif ($info['password'] != md5($old_pwd)) {
            $this->ajax_return(FLAG_ERROR, '旧密码不正确！');
        }
        $flag = $model->edit($user_id, array('password'=>md5($password)));
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '修改密码失败！');
        }
        $this->ajax_return(FLAG_OK, '操作成功！');
    }


    /**
     * 找回密码，发送验证码
     * @author mashimaro
     * @date 2015/03/04
     */
    public function findPwdVerify () {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $phone_mob = $this->get_gp('phone_mob', 'G');
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度为11位，请您重新输入！');
        } elseif (!$this->is_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号格式不正确！');
        }
        $info = $this->get_member_info_by_phone($phone_mob);
        if (!$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户信息不存在！');
        }
        /**生成四位随机数的验证码**/
        $verify_code = '';
        for ($i = 0; $i < 4; $i++) {
            $verify_code .= rand(0, 9);
        }
        $sms = ms('smslogs');
        $sms_model = m('smslogs');
        //数据入库
        $flag = $sms_model->add(array('phone_mob'=>$phone_mob,'verify_code'=>$verify_code,'created_at'=>time()));
        if (!$flag) {
            $this->ajax_return(FLAG_ERROR, '存储数据信息失败！');
        }
        /**发送手机验证码**/
        $rs = $sms->pm->send($phone_mob, $verify_code);
        if ($rs['code'] != 2) {
            $this->ajax_return(FLAG_ERROR, $rs['msg']);
        }
        $this->ajax_return(FLAG_OK, "发送短信验证码成功！");
    }

    /**
     * 忘记密码，修改信息
     * @author mashimaro
     * @date 2015/03/04
     */
    public function findPwd() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $phone_mob = $this->get_gp('phone_mob', 'P');
        $verify = $this->get_gp('verify_code', 'P');
        $password = $this->get_gp('password', 'P');
        $pwd = $this->get_gp('pwd', 'pwd');

        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度为11位，请您重新输入！');
        } elseif (!$this->is_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号格式不正确！');
        }
        $model = m('member');
        $sql = "SELECT sms_id,phone_mob,verify_code,created_at FROM ".DB_PREFIX."sms_logs WHERE phone_mob='{$phone_mob}' ORDER BY sms_id DESC LIMIT 1";
        $sms = $model->getRow($sql);
        if (!$verify) {
            $this->ajax_return(FLAG_ERROR, '验证码不能为空，请您重新输入！');
        } elseif (strlen($verify) != 4) {
            $this->ajax_return(FLAG_ERROR, '验证码长度为4位，请您重新输入！');
        } elseif (!$this->is_number($verify)) {
            $this->ajax_return(FLAG_ERROR, '验证码格式不正确，请您重新输入！');
        } elseif ($sms['verify_code'] != $verify) {
            $this->ajax_return(FLAG_ERROR, '非法的验证码，请您重新输入！');
        }
        //验证码超时，有效时间10分钟
        if (time() - $sms['created_at'] > 600) {
            $this->ajax_return(FLAG_ERROR, '验证码超时，请您重新获取！');
        }
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, '密码不能为空，请您重新输入！');
        }
        if ($password != $pwd) {
            $this->ajax_return(FLAG_ERROR, '密码不一致，请您重新输入！');
        }

        //获取用户信息

        $info = $model->get(array('conditions'=>"phone_mob={$phone_mob}"));
        if (!$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户信息不存在！');
        }
        $flag = $model->edit($info['user_id'], array('password'=>md5($password)));
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '更新用户信息失败！');
        }
        $this->ajax_return(FLAG_OK, '修改密码成功！');
    }

    /**
     * 上传头像
     * @author mashimaro
     * @date 2015/02/28
     */
    public function uploadAvatar() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $config = require ROOT_PATH . '/data/config.qiniu.php';
        $user_id = $this->get_gp('user_id', 'P');
        $user_id = $user_id ? intval($user_id) : 0;
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $file = $_FILES['file'];
        if ($file['error'] != UPLOAD_ERR_OK) {
            $this->ajax_return(FLAG_ERROR, '上传图片错误！');
        }
        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->addFile($file);

        //获取原来的头像信息
        $model = m('member');
        $info = $model->get(array(
            'conditions'    => "user_id={$user_id}",
            'fields'        => 'portrait',
        ));
        //七牛云上传图片
        $filename = $uploader->random_filename();
        $filename = 'data/files/mall/portrait/'.$filename.$user_id.'.gif';
        $filename = $this->fileUpload($filename,$file['tmp_name'], 100, 100);
        if ($filename === false) {
            $this->ajax_return(FLAG_ERROR, '上传七牛图片失败！');
        }
        //更新头像信息
        $flag = $model->edit($user_id, array('portrait'=>$filename));
        if ($flag === false) {
            $this->delFileQiNiu($filename);//如果上传不成功，则删除刚上传的头像
            $this->ajax_return(FLAG_ERROR, '更新头像数据信息失败');
        }
        //删除原来七牛上的文件
        if ($info['portrait']) {
            $this->delFileQiNiu($info['portrait']);
        }
        $this->ajax_return(FLAG_OK, '', array('portrait'=>$config['qiniu_url'].$filename));
    }

    /**
     * 根据手机号获取用户信息
     * @param $phone_mob
     * @return array
     * @author jiayanxiu
     * @date 2015/01/09
     */
    private function get_member_info_by_phone($phone_mob) {
        $model = m('member');
        $info = $model->get("phone_mob='{$phone_mob}'");
        return $info;
    }

    /**
     * 根据用户名或手机号获取用户信息
     * @param $content
     * @return array
     * @author jiayanxiu
     * @date 2015-01-09
     */
    private function get_member_info($content) {
        $model = m('member');
        $info = $model->get("user_name='{$content}' or phone_mob='{$content}'");
        return $info;
    }

    /**
     * 获取手机短信日志信息
     * @param $phone_mob
     * @return mixed
     * @author jiayanxiu
     * @date 2015-01-11
     */
    private function get_sms_logs_info($phone_mob) {
        $start = strtotime(date('Y-m-d 00:00:00'));
        $end = strtotime(date('Y-m-d 23:59:59'));
        $model = m('smslogs');
        $info = $model->get(array('conditions'=>"phone_mob={$phone_mob}",'order'=>'sms_id DESC','limit'=>1));
        $row = $model->get(array(
            'fields'=>'COUNT(*) AS count',
            'conditions'=>"phone_mob={$phone_mob} AND created_at > {$start} AND created_at <= {$end}",
        ));
        $info['count'] = $row['count'];
        return $info;
    }

    /**
     * 检查用户名是否唯一
     * @param $user_name
     * @return boolean
     * @author jiayanxiu
     * @date 2015/01/08
     */
    private function check_username($user_name) {
        $model_member = m('member');
        $info = $model_member->get("user_name='{$user_name}'");
        if ($info['user_name']) {
            return false;
        }

        return true;
    }

    /**
     * 检查手机号码是否唯一
     * @param $phone_number
     * @return boolean
     * @author jiayanxiu
     * @date 2015/01/08
     */
    private function check_phone($phone_mob) {
        $model_member = m('member');
        $info = $model_member->get("phone_mob='{$phone_mob}'");
        if ($info['phone_mob']) {
            return false;
        }

        return true;
    }
}